package com.cdut.interceptor;

import com.cdut.pojo.User;
import com.cdut.service.UserService;
import com.cdut.util.JsonResponce;
import org.apache.shiro.subject.PrincipalCollection;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.servlet.HandlerInterceptor;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.UsernamePasswordToken;
import org.apache.shiro.session.Session;
import org.apache.shiro.subject.Subject;
import org.springframework.web.servlet.ModelAndView;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * 自动记住我的过滤器
 */

public class RememberMeInterceptor implements HandlerInterceptor {

    @Autowired
    private UserService userService;

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object o) throws Exception {

        Subject currentUser = SecurityUtils.getSubject();
        //判断用户是通过记住我功能自动登录,此时session失效
        if (!currentUser.isAuthenticated() && currentUser.isRemembered()) {
            PrincipalCollection principals = currentUser.getPrincipals();
            String username = null;

            for (Object principal : principals) {
                if (principal.getClass()==User.class){
                    System.out.println(principal);
                     username =  ((User) principal).getUsername();
                }
            }

            JsonResponce<User> jsonResponce = userService.queryUserByName(username);
            System.out.println("[rememberMeInterceptor]:"+username);
            System.err.println("[rememberMeInterceptor]:"+currentUser.getPrincipal().toString());
            User user = jsonResponce.getData();

            Session session = currentUser.getSession();
            System.err.println("[interceptor]:"+user);
            session.setAttribute("loginUser", user);
        }

        return true;
    }

    @Override
    public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) throws Exception {

    }

    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {

    }

    public RememberMeInterceptor() {

    }
}